import axios from "axios";

/**
 * @description: 创建axios实例对象
 * @author: 王琛
 * @Date: 2023-05-30 14:42:54
 * @param {*}
 * @return {*}
 */
const http = axios.create({
    baseURL: import.meta?.env?.VITE_MODE_MAIN_REQ_IP || 'http://localhost:3000',
    timeout: 50000,
});
/**
 * @description: 请求前拦截
 * @author: 王琛
 * @Date: 2023-05-30 14:42:34
 * @param {*}
 * @return {*}
 */
http.interceptors.request.use(
    (config) => {
        return config;
    }
)

/**
 * @description: 响应后拦截
 * @author: 王琛
 * @Date: 2023-05-30 14:42:42
 * @param {*}
 * @return {*}
 */
http.interceptors.response.use(
    (response) => {
        return response.data;
    }, (err) => {
        return Promise.reject(err.response.data)
    }
)

/**
 * @description: 统一请求接口方法
 * @author: 王琛
 * @Date: 2023-05-30 14:44:24
 * @param {*}
 * @return {*}
 */
interface Config {
    url: string,
    method: string,
    data?: any,
    params?: any,
    headers?: any,

    // 其他参数
    [key: string]: any

}

async function request({url, method, params, headers, config}: Config) {
    try {
        const modeList = ["put", "post", "patch"];
        // 创建config ts类型接口
        const _config: Config = {
            url,
            method,
            [modeList.includes(method) ? 'data' : 'params']: params,
            headers,
            ...config
        }
        return await http.request(_config);
    } catch (err) {
        console.log('%c日志-100152', 'color:#fff;fontSize:15px;background:#993366;padding:2px 5px;border-radius:6px', "请求错误响应:", err);

    }

}

export default request;